package com.lzx.adx.report.controller.v1.youku;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.KjbCovertYoukuEventTypeEnums;
import com.lzx.adx.report.model.youku.AdConvInfo;
import com.lzx.adx.report.model.youku.YouKuElmRequest;
import com.lzx.adx.report.model.youku.YouKuKey;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.SignUtil;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/youku/cz/tcly")
@RestController
@Slf4j
@RequiredArgsConstructor
public class YouKuCzController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final   String apiDesc="优酷-同城旅行";


    @GetMapping("/report")
    public ResponseEntity report(YouKuElmRequest youKuElmRequest, HttpServletRequest request){
        log.info("接收到【{}】的请求参数为{}",apiDesc, JsonUtils.toJsonString(youKuElmRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(youKuElmRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(youKuElmRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis()/1000));
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(youKuElmRequest.getDspId());

        String finalUrl= KkHeper.covertChuangZhiUrl(accountDTO,youKuElmRequest,reportDTO);

        log.info("账号为{},完整的优酷-创智 请求地址为{}",youKuElmRequest.getDspId(),finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 优酷接收了-创智，上报的接口，响应的结果为{}",youKuElmRequest.getDspId(),body);


        return ResponseEntity.ok(new Result());
    }





    /**
     * 创智回传
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId,String tnaEvent) throws Exception {
        log.info("优酷 接收了 创智 回调信息，请求流水号{}",requestId);

        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="active";
        }


        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId",requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //2.从缓存加载配置
        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        YouKuElmRequest youKuElmRequest = JSONObject.parseObject(reportDTO.getExtend(), YouKuElmRequest.class);

        //获取请求的API地址
        String sspApiUrl = accountDTO.getSspApiUrl();
        YouKuKey youKuKey = JSONObject.parseObject(accountDTO.getSspExtend(), YouKuKey.class);


        Map<String, Object> param = new HashMap<>();
        param.put("event_type", "active");
        param.put("event_time", reportDTO.getResultTime());
        param.put("track_id", youKuElmRequest.getTrackId());
        param.put("deep_conv", 0);
        param.put("creative_id", youKuElmRequest.getContentId());//必须是数字

        AdConvInfo advConvInfo = new AdConvInfo();
        advConvInfo.setAppKey(youKuKey.getAppKey());//需要替换
        advConvInfo.setContent(param);
        advConvInfo.setSignature(SignUtil.sign(advConvInfo.getAppKey(), youKuKey.getToken(), toStr(advConvInfo.getContent())));

        String paramsData=JSON.toJSONString(advConvInfo);
        String post = HttpUtil.post(sspApiUrl,paramsData );


        return ResponseEntity.ok(new Result());
    }






    public static String toStr(Map<String, Object> params) {
        if (CollectionUtil.isEmpty(params)) {
            return null;
        }
        List<String> paramNameList = Lists.newArrayList();
        paramNameList.addAll(params.keySet());
        Collections.sort(paramNameList);
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (String key : paramNameList) {
            if (first) {
                first = false;
            } else {
                builder.append("&");
            }
            builder.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            builder.append(valueString);
        }
        return builder.toString();
    }

}
